package com.msmall.community.album.dao.hibernate;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.msmall.base.dao.hibernate.BaseDaoHibernate;
import com.msmall.community.album.dao.AlbumDao;
import com.msmall.community.album.model.Album;
import com.msmall.community.album.model.Photo;
import com.msmall.community.album.model.Reply;

@SuppressWarnings("rawtypes")
public class AlbumDaoHibernate extends BaseDaoHibernate implements AlbumDao{

	private static final Log logger = LogFactory.getLog(AlbumDaoHibernate.class);
	
	/**
	 * 获得用户所有的相册列表:Album, Photo
	 * <br/>
	 * 同时获得相册的封面，如果封面为NULL.使用默认封面
	 */
	@SuppressWarnings("unchecked")
	public List<Object[]> getAlumsByUserid(Long userid) throws Exception{
		try{
			String sql= "SELECT a.*, p.* FROM base_album AS a LEFT JOIN base_album_photo AS p " +
					" ON a.photo_id=p.photo_id " +
					" WHERE a.user_id=?";
			Session session = super.getSession();
			SQLQuery query = session.createSQLQuery(sql).addEntity(Album.class).addEntity(Photo.class);
			query.setParameter(0, userid);
			List list = query.list();
			super.releaseSession(session);
			return list;
		}catch(Exception e){
			logger.debug(e);
			throw e;
		}
	}
	
	/**
	 * 删除相册时，移动相片所属相册
	 * @param albumid 被删除的相册ID
	 * @param targetid 相片被移动到
	 */
	public void updatePhotoAlbum(Long albumid, Long targetid, Long userid) throws Exception{
		try{
			final String tempsql = "UPDATE base_album_photo SET album_id=" + targetid
					+ " WHERE album_id="+albumid;
			getHibernateTemplate().execute(new HibernateCallback(){
				public Object doInHibernate(Session session)throws HibernateException{
					session.createSQLQuery(tempsql).executeUpdate();
					return null;
				}
			});
		}catch(Exception e){
			logger.debug(e);
			throw e;
		}
	}
	/**
	 * 获得图片的所有评论
	 */
	public List<Reply> getReplysByPhotoid(Long photoid, Short enabled)throws Exception{
		try{
			String tempsql = "FROM Reply where photoid=?";
			if(enabled != null){
				tempsql += " AND enabled=?";
				return getHibernateTemplate().find(tempsql, new Object[]{photoid, enabled});
			}else{
				return getHibernateTemplate().find(tempsql, new Object[]{photoid});
			}
		}catch(Exception e){
			logger.debug(e);
			throw e;
		}
	}
	
	/**
	 * 通过id查找照片的前一张图片,按ID排序，如果是第一张，跳到最后一张，同时增加图片访问次数
	 */
	public Photo getPhotoPreByid(Long photoid) throws Exception{
		try{
			StringBuffer buffer = new StringBuffer();
			buffer.append("select a.* from base_album_photo a,")
			.append(" ( select b.album_id FROM base_album_photo b where b.photo_id=? ) c ")
			.append(" where a.album_id=c.album_id and a.photo_id<? ORDER BY a.photo_id DESC limit 1");
			Session session = super.getSession();
			SQLQuery query = session.createSQLQuery(buffer.toString()).addEntity(Photo.class);
			query.setParameter(0, photoid);
			query.setParameter(1, photoid);
			List list = query.list();
			if(list != null && list.size() >0){
				return (Photo) list.get(0);
			}
			super.releaseSession(session);
			return null;
		}catch(Exception e){
			logger.debug(e);
			throw e;
		}
	}
	
	/**
	 * 通过id查找照片的后一张图片,按ID排序，如果是最后一张，跳到第一张，同时增加图片访问次数
	 */
	public Photo getPhotoNextByid(Long photoid) throws Exception{
		StringBuffer buffer = new StringBuffer();
		buffer.append("select a.* from base_album_photo a,")
		.append(" ( select b.album_id FROM base_album_photo b where b.photo_id=? ) c ")
		.append(" where a.album_id=c.album_id and a.photo_id>? ORDER BY a.photo_id ASC limit 1");
		Session session = super.getSession();
		SQLQuery query = session.createSQLQuery(buffer.toString()).addEntity(Photo.class);
		query.setParameter(0, photoid);
		query.setParameter(1, photoid);
		List list = query.list();
		if(list != null && list.size() >0){
			return (Photo) list.get(0);
		}
		super.releaseSession(session);
		return null;
	}
}
